# [Cpp] ๊ฐ€์ƒ ํ•จ์ˆ˜(Virtual function)



C++์—์„œ ์ž์‹ ํด๋ž˜์Šค์—์„œ ์žฌ์ •์˜(์˜ค๋ฒ„๋ผ์ด๋”ฉ)ํ•  ๊ฒƒ์œผ๋กœ ๊ธฐ๋Œ€ํ•˜๋Š” ๋ฉค๋ฒ„ ํ•จ์ˆ˜๋ฅผ ์˜๋ฏธํ•จ

๋ฉค๋ฒ„ ํ•จ์ˆ˜ ์•ž์— virtual ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์„ ์–ธํ•จ โ†’ ์‹คํ–‰์‹œ๊ฐ„์— ํ•จ์ˆ˜์˜ ๋‹คํ˜•์„ฑ์„ ๊ตฌํ˜„ํ•  ๋•Œ ์‚ฌ์šฉ


# ์„ ์–ธ ๊ทœ์น™

  • ํด๋ž˜์Šค์˜ public ์˜์—ญ์— ์„ ์–ธํ•ด์•ผ ํ•œ๋‹ค.

  • ๊ฐ€์ƒ ํ•จ์ˆ˜๋Š” static์ผ ์ˆ˜ ์—†๋‹ค.

  • ์‹คํ–‰์‹œ๊ฐ„ ๋‹คํ˜•์„ฑ์„ ์–ป๊ธฐ ์œ„ํ•ด, ๊ธฐ๋ณธ ํด๋ž˜์Šค์˜ ํฌ์ธํ„ฐ ๋˜๋Š” ์ฐธ์กฐ๋ฅผ ํ†ตํ•ด ์ ‘๊ทผํ•ด์•ผ ํ•œ๋‹ค.

  • ๊ฐ€์ƒ ํ•จ์ˆ˜๋Š” ๋ฐ˜ํ™˜ํ˜•๊ณผ ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ์ž์‹ ํด๋ž˜์Šค์—์„œ๋„ ์ผ์น˜ํ•ด์•ผ ํ•œ๋‹ค.


class parent {
public :
    virtual void v_print() {
        cout << "parent" << "\n";
    }
    void print() {
        cout << "parent" << "\n";
    }
};
 
class child : public parent {
public :
    void v_print() {
        cout << "child" << "\n";
    }
    void print() {
        cout << "child" << "\n";
    }
};
 
int main() {
    parent* p;
    child c;
    p = &c;
 
    p->v_print();
    p->print();
 
    return 0;
}

[์ถœ๋ ฅ ๊ฒฐ๊ณผ]
child
parent

parent ํด๋ž˜์Šค๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ํฌ์ธํ„ฐ p๋ฅผ ์„ ์–ธํ•˜๊ณ  child ํด๋ž˜์Šค์˜ ๊ฐ์ฒด c๋ฅผ ์„ ์–ธํ•œ ์ƒํƒœ

ํฌ์ธํ„ฐ p๊ฐ€ c ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ณ  ์žˆ์Œ (๋ชธ์ฒด๋Š” parent ํด๋ž˜์Šค์ง€๋งŒ, ํ˜„์žฌ ์‹ค์ œ ๊ฐ์ฒด๋Š” child ํด๋ž˜์Šค)

ํฌ์ธํ„ฐ p๋ฅผ ํ™œ์šฉํ•ด virtual์„ ํ™œ์šฉํ•œ ๊ฐ€์ƒ ํ•จ์ˆ˜์ธ v_print()์™€ ์˜ค๋ฒ„๋ผ์ด๋”ฉ๋œ ํ•จ์ˆ˜ print()์˜ ์ถœ๋ ฅ์€ ๋‹ค๋ฅด๊ฒŒ ๋‚˜์˜ค๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

๊ฐ€์ƒ ํ•จ์ˆ˜๋Š” ์‹คํ–‰์‹œ๊ฐ„์— ๊ฐ’์ด ๊ฒฐ์ •๋จ (ํ›„๊ธฐ ๋ฐ”์ธ๋”ฉ)

print()๋Š” ์ปดํŒŒ์ผ ์‹œ๊ฐ„์— ์ด๋ฏธ ๊ฒฐ์ •๋˜์–ด parent๊ฐ€ ํ˜ธ์ถœ๋˜๋Š” ๊ฒƒ์œผ๋กœ ๊ฒฐ์ •์ด ๋๋‚จ

์ตœ์ข… ์ˆ˜์ • : 12/17/2022, 7:23:59 AM